package com.loong.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loong.entity.Word;
import com.loong.entity.WordBook;
import com.loong.service.impl.WordBookServiceImpl;
import com.loong.service.impl.WordServiceImpl;
import com.loong.util.WordSearchUtil;
import com.loong.util.YamlReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author loong
 * @since 2024-12-08
 */
@RestController
@RequestMapping("/word")
public class WordController {


    @Autowired
    private WordServiceImpl wordService;

    @Autowired
    private WordBookServiceImpl wordBookService;

    @GetMapping("/getTargetWords")
    public List<String> getTargetWords(@RequestParam("word") String word){

        YamlReader.loadResource("/application.yml");
        String path=(String) YamlReader.getValueByKey("words.outputDir");
        // 在字典库中查找，查找前15个以word开头的单词返回，返回Word类
        return WordSearchUtil.searchWordsInOrder(word,path);
    }

    /**
     * 用户下拉候选单词列表的时候，返回新的单词
     * @param page
     * @param word
     * @return
     */
    @GetMapping("/getMoreWords")
    public List<String> getMoreWords(@RequestParam("page")Integer page,@RequestParam("word")String word){
        YamlReader.loadResource("/application.yml");
        String path=(String) YamlReader.getValueByKey("words.outputDir");

        return WordSearchUtil.searchWordsInOrder(word,page,path);
    }

    @PostMapping("/addWord")
    public Word addWord(@RequestBody Word form){
        wordService.save(form);
        WordBook wordBook = wordBookService.getById(form.getWordBookId());
        wordBook.setWordCount(wordBook.getWordCount()+1);
        wordBookService.saveOrUpdate(wordBook);
        return form;
    }

    @GetMapping("/getWordsByBookId")
    public List<Word> getWordsByBookId(@RequestParam("wordBookId")Integer bookId,@RequestParam("page")Integer page){

        Page<Word> wordPage = new Page<>(page,5);
        LambdaQueryWrapper<Word> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Word::getWordBookId,bookId);
        Page<Word> result = wordService.page(wordPage,queryWrapper);
        return result.getRecords();
    }

    @DeleteMapping("/deleteById")
    public boolean deleteById(@RequestParam("id") Long id){
        Word word = wordService.getById(id);
        wordService.removeById(id);
        WordBook wordBook = wordBookService.getById(word.getWordBookId());
        wordBook.setWordCount(wordBook.getWordCount()-1);
        wordBookService.saveOrUpdate(wordBook);
        return true;
    }
}
